package io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.datasource.DatasourceApi;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.model.LogDTO;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.Elasticsearch;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.enums.DateSuffixEnum;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.properties.enums.EsIndexTypeEnum;
import io.github.flypiggy.stack.operate.log.spring.boot.starter.utils.DateTimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class ElasticsearchRepository implements DatasourceApi {

    private final Logger log = LoggerFactory.getLogger(ElasticsearchRepository.class);

    private final ElasticsearchClient client;
    private final Boolean haveSuffix;
    private final String baseIndex;
    private final String pattern;

    public ElasticsearchRepository(ElasticsearchClient client, Elasticsearch.Index index) {
        this.client = client;
        this.baseIndex = index.getName();
        this.haveSuffix = EsIndexTypeEnum.DATE_SUFFIX.equals(index.getType());
        this.pattern = this.haveSuffix ? DateSuffixEnum.getEsSuffixPattern(index.getSuffix()) : "";
    }

    @Override
    public void save(LogDTO logDTO) {
        String index = haveSuffix
                ? this.baseIndex + DateTimeUtils.format(logDTO.getCreateTime(), pattern)
                : this.baseIndex;
        try {
            client.create(e -> e.index(index).id(logDTO.getId().toString()).document(logDTO));
        } catch (IOException e) {
            log.warn("OPERATE-LOG Store elasticsearch document exception.This exception will not affect your main program flow, but operation logging cannot be saved.", e);
        }
    }
}
